<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p>得分：<b>0</b></p>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body,
        html {
            height: 100%;
        }

        span {
            width: 40px;
            height: 40px;
            background-color: red;
            color: white;
            border-radius: 50%;
            display: block;
            text-align: center;
            line-height: 40px;
            font-size: 24px;
            font-weight: bold;
            position: absolute;
            top: 0;
            left: 0
        }
    </style>
</body>

</html>
<script>
    //思路
    // 字母球从上往下掉落，掉落到底部消毁，
    // 在掉落期间输入了正确的字母或数字，得分加一然后重新生成小球
    //创建span标签 分配一个字符 控制span标签的横向位置 控制span标签的纵向位置
    let span;
    let score = 0;
    let timer;

    function makeRandom(min, max) {
        return (parseInt)(Math.random() * (max - min) + min);
    }

    function makeRandomChar() {
        let str = "zxcvbnmasdfghjklqwertyuiop23456789";
        //获取一个随机下标
        let index = makeRandom(0, str.length);
        console.log(index);
        return str[index];
    }

    function createTag() {
        //创建span标签
        span = document.createElement('span');
        span.innerHTML = makeRandomChar();
        document.body.appendChild(span);
        let leftMax = document.documentElement.clientWidth - span.clientWidth
        let left = makeRandom(0, leftMax);
        span.style.left = left + 'px';
        //使用定时器
        timer = setInterval(function () {
            let maxTop = document.documentElement.clientHeight - span.clientHeight;
            let current = parseFloat(getComputedStyle(span).top)
            if (current < maxTop) {
                span.style.top = current + 1 + 'px';
                return;
            }
            clearInterval(timer);
            document.body.removeChild(span);
            createTag();

        })
    }

    document.addEventListener('keypress', function () {
        console.log(event.key);
        if (event.key == span.innerHTML) {
            score++
            document.querySelector('b').innerHTML = score;
            clearInterval(timer);
            document.body.removeChild(span);
            createTag();
        }
    })

    createTag();
</script>